package cn.wbnyua.msm.util;

import cn.wbnyua.msm.core.exception.RuntimeExceptionHandler;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 作者：wbnyua.
 * 创建时间: 2023/2/9 11:31.
 */
@Component
public class JwtToken {


    private static String jwtKey;
    private static Integer expiredTimeIn;
    private static Integer defaultScope = 8;
    @Value("${wbnyua.security.jwt-key}")
    public void setJwtKey(String jwtKey){
        JwtToken.jwtKey = jwtKey;
    }

    @Value("${wbnyua.security.token-expired-in}")
    public void setExpiredTimeIn(Integer expiredTimeIn){
        JwtToken.expiredTimeIn = expiredTimeIn;
    }


    public static String makeToken(Long uid,Integer scope){
        return getToken(uid,defaultScope);
    }

    public static String getToken(Long uid,Integer scope){
        Algorithm algorithm = Algorithm.HMAC256(jwtKey);
        Map<String,Date> map = calcExpiredIssues();
        String token = JWT.create()
                .withClaim("uid", uid)
//                .withClaim("scope",scope)
                .withExpiresAt(map.get("expiredTime"))
                .withIssuedAt(map.get("now"))
                .sign(algorithm);
        return token;
    }

    public static Long getUserId(String token){
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            return decodedJWT.getClaim("uid").asLong();
        }catch (JWTDecodeException e){
            throw new RuntimeExceptionHandler("token校验失败");
        }
    }

    public static Map<String, Claim> getClaims(String token){
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            return decodedJWT.getClaims();
        }catch (JWTDecodeException e){
            throw new RuntimeExceptionHandler("token校验失败");
        }
    }


    private static Map<String, Date> calcExpiredIssues(){
        Map<String,Date> map = new HashMap<>();
        Calendar calendar = Calendar.getInstance();
        Date now = calendar.getTime();
        calendar.add(Calendar.SECOND,JwtToken.expiredTimeIn);
        map.put("now",now);
        map.put("expiredTime",calendar.getTime());
        return map;
    }


}
